import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/db/love_database.dart';
import 'package:wallpaper/tools/down_image.dart';
import 'package:wallpaper_manager_plus/wallpaper_manager_plus.dart';

// ignore: must_be_immutable
class ImageView extends StatefulWidget {
  final List images;
  int selectedIndex;
  final VoidCallback resetGetdata;
  bool isMobile = false;
  ImageView({
    super.key,
    required this.images,
    required this.selectedIndex,
    required this.resetGetdata,
    this.isMobile = false,
  });

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  final PanelController _panelController = PanelController();
  bool isLove = false;
  double iconSize = 30;
  late PageController _pageController;
  bool _isImageScaled = false; // 跟踪图片是否被缩放
  double _currentScale = 1.0; // 当前缩放比例

  void isLoveGet() async {
    bool res = await context.read<LoveDatabase>().isLove(widget.isMobile
        ? widget.images[widget.selectedIndex].largePath
        : widget.images[widget.selectedIndex].smallPath);
    setState(() {
      isLove = res;
    });
  }

  void downLoad() async {
    // 下载图片到相册
    String path = await DownImage.downloadNetworkImage(
        widget.images[widget.selectedIndex].largePath);
    if (path != 'error') {
      _panelController.close();
    }
  }

  void shareImage() async {
    // 分享图片 复制图片地址到剪贴板
    Clipboard.setData(
        ClipboardData(text: widget.images[widget.selectedIndex].largePath));
    BotToast.showText(text: "已复制图片链接");
  }

  void setWallpaper() async {
    // 弹出壁纸类型选择对话框
    final int? location = await showDialog<int>(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: const Color.fromARGB(50, 0, 0, 0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        elevation: 6,
        shadowColor: Colors.black26,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildListTitle('桌面壁纸', '仅修改主屏幕背景', Icons.phone_android, () {
                Navigator.pop(context, WallpaperManagerPlus.homeScreen);
              }),
              _buildListTitle('锁屏壁纸', '仅修改锁屏界面背景', Icons.lock_rounded, () {
                Navigator.pop(context, WallpaperManagerPlus.lockScreen);
              }),
              _buildListTitle('同时设置', '统一主屏和锁屏壁纸', Icons.phonelink_setup, () {
                Navigator.pop(context, WallpaperManagerPlus.bothScreens);
              }),
              NormalButton(
                title: '取消',
                onPressed: () {
                  Navigator.pop(context);
                },
                bgColor: const Color.fromARGB(60, 255, 255, 255),
              ),
            ],
          ),
        ),
      ),
    );

    if (location == null) return;
    _panelController.close();

    var loadingBot = BotToast.showCustomLoading(
        backgroundColor: const Color.fromARGB(100, 4, 4, 4),
        toastBuilder: (cancel) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MyLoading(type: 2),
              SizedBox(height: 10),
              Text(
                '设置中，请稍后···',
                style: TextStyle(color: Colors.white, fontSize: 13),
              ),
            ],
          );
        });

    try {
      // 下载图片
      final path = await DownImage()
          .setWallpaper(widget.images[widget.selectedIndex].largePath);
      if (path == null) {
        return;
      }

      // 设置壁纸
      // final result =
      //     await WallpaperManager.setWallpaperFromFile(path, location);
      await WallpaperManagerPlus().setWallpaper(File(path), location);
      BotToast.showText(text: "设置成功");
    } catch (e) {
      BotToast.showText(text: "设置失败", contentColor: Colors.red);
    } finally {
      loadingBot();
    }
  }

  void changeLove() {
    setState(() {
      isLove = !isLove;
    });
    context.read<LoveDatabase>().addLove(
        widget.isMobile
            ? widget.images[widget.selectedIndex].largePath
            : widget.images[widget.selectedIndex].smallPath,
        widget.images[widget.selectedIndex].largePath,
        widget.images[widget.selectedIndex].tags);
    widget.resetGetdata();
  }

  @override
  void initState() {
    super.initState();
    isLoveGet();
    _pageController = PageController(initialPage: widget.selectedIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          color: Colors.black,
          // 导航栏字体颜色
          child: AnnotatedRegion<SystemUiOverlayStyle>(
            value: SystemUiOverlayStyle.light,
            child: Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    _panelController.isPanelOpen
                        ? _panelController.close()
                        : _panelController.open();
                  },
                  child: PageView.builder(
                    controller: _pageController,
                    scrollDirection: Axis.vertical,
                    physics: _isImageScaled
                        ? const NeverScrollableScrollPhysics() // 缩放时禁用滚动
                        : const ClampingScrollPhysics(), // 正常状态允许滚动
                    itemCount: widget.images.length,
                    itemBuilder: (context, index) =>
                        _buildImageView(widget.images[index].largePath),
                    onPageChanged: (index) {
                      setState(() {
                        widget.selectedIndex = index;
                        isLoveGet();
                      });
                    },
                  ),
                ),
                // 滑动面板
                SlidingUpPanel(
                  color: const Color.fromARGB(25, 0, 0, 0),
                  controller: _panelController,
                  minHeight: 0, // 面板最小高度
                  maxHeight: 200, // 最大高度为屏幕 30%
                  borderRadius:
                      BorderRadius.vertical(top: Radius.circular(5.0)),
                  parallaxEnabled: true, // 启用视差效果
                  parallaxOffset: 0.2, // 视差偏移量
                  backdropEnabled: false, // 背景遮罩
                  backdropOpacity: 0, // 背景遮罩不透明度
                  panel: _buildPanelContent(), // 面板内容
                  collapsed: null, // 收起时的显示内容
                  onPanelOpened: () => {},
                  onPanelClosed: () => {},
                ),
              ],
            ),
          )),
    );
  }

  Widget _buildImageView(String imagePath) {
    return ExtendedImage.network(
      imagePath,
      width: double.infinity,
      height: double.infinity, // 屏幕高度
      fit: BoxFit.fitWidth,
      cache: true,
      mode: ExtendedImageMode.gesture,
      initGestureConfigHandler: (state) {
        return GestureConfig(
          // 缩放最小值
          minScale: 1,
          // 缩放动画最小值 当缩放结束时回到 minScale 值
          animationMinScale: 0.5,
          // 缩放最大值
          maxScale: 3.0,
          // 缩放动画最大值 当缩放结束时回到 maxScale 值
          animationMaxScale: 4.0,
          // 缩放拖拽速度
          speed: 1.0,
          // 拖拽惯性速度
          inertialSpeed: 100.0,
          initialScale: 1.0,
          // 是否使用 ExtendedImageGesturePageView 展示图片
          inPageView: true,
          // 当图片的初始化缩放大于 1.0 的时候，根据相对位置初始化图片
          initialAlignment: InitialAlignment.center,
          gestureDetailsIsChanged: (details) {
            // 缩放时更新状态
            final scale = details?.totalScale != 1.0 ? 2.0 : 1.0;
            // 更新缩放状态的方法
            setState(() {
              _isImageScaled = scale > 1.0;
              _currentScale = scale;
            });
          },
        );
      },

      /// 加载状态回调
      loadStateChanged: (ExtendedImageState state) {
        switch (state.extendedImageLoadState) {
          /// 加载中
          case LoadState.loading:
            return MyLoading(
              type: 3,
              size: 50,
            );

          /// 加载成功
          case LoadState.completed:
            return state.completedWidget;

          /// 加载失败
          case LoadState.failed:
            // 自己写的加载失败的组件 并且把重试的回调传递过去
            return Center(
              child: Icon(
                Icons.perm_media,
                color: Theme.of(context).colorScheme.primaryContainer,
                size: 50,
              ),
            );
        }
      },
      onDoubleTap: (state) {
        // 双击缩放时更新状态
        final scale = _currentScale != 1.0 ? 1.0 : 2.0;
        state.handleDoubleTap(scale: scale);
        // 更新缩放状态的方法
        setState(() {
          _isImageScaled = scale > 1.0;
          _currentScale = scale;
        });
      },
    );
  }

  // 面板展开时的内容
  Widget _buildPanelContent() {
    return Column(
      children: [
        // 拖拽提示条
        GestureDetector(
          onTap: () => _panelController.close(),
          child: Container(
            margin: EdgeInsets.symmetric(vertical: 10),
            height: 5,
            width: 50,
            decoration: BoxDecoration(
              color: const Color.fromARGB(50, 255, 255, 255),
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        ),
        SizedBox(height: 15),
        Flex(
          direction: Axis.horizontal,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _buildOperationButton(Icons.favorite, '收藏', () {
              changeLove();
            }, isLove),
            _buildOperationButton(Icons.download, '下载', () {
              downLoad();
            }),
            _buildOperationButton(Icons.share, '分享', () {
              shareImage();
            }),
            _buildOperationButton(Icons.phone_android_rounded, '壁纸', () {
              setWallpaper();
            }),
          ],
        ),
      ],
    );
  }

  Widget _buildOperationButton(IconData icon, String title, Function() onTap,
      [isLove = false]) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          onPressed: onTap,
          icon: Icon(
            icon,
            size: iconSize,
            color: isLove ? Colors.red : Colors.white,
          ),
        ),
        Text(
          title,
          style: TextStyle(
            color: Colors.white,
            fontSize: 13,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  Widget _buildListTitle(
      String title, String subtitle, IconData icon, Function onTap) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 3),
      child: ListTile(
        // 圆角
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        contentPadding: EdgeInsets.symmetric(horizontal: 10),
        title: Text(title, style: TextStyle(color: Colors.white)),
        subtitle: Text(subtitle, style: TextStyle(color: Colors.white)),
        leading: Icon(icon, color: Colors.white),
        trailing: Icon(Icons.arrow_forward_ios, color: Colors.white),
        onTap: () => onTap(),
      ),
    );
  }
}
